package com.example.yckjbigdataservice.controller;

import com.example.yckjbigdataservice.utils.ResilientRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RequestMapping("/redis")
@RestController
@Slf4j
public class RedisController {

    private final static long ttl = 10000; // 10 秒

    private final JedisCluster jedisCluster;

    public RedisController(JedisCluster jedisCluster) {
        this.jedisCluster = jedisCluster;
    }

    @GetMapping("/test/lock")
    public String testLock(@RequestParam String requestId) {
        /*if (redisProperties.getCluster() != null) {
            // 初始化 ClusterServersConfig
        } else {
            // 单节点配置
            config.useSingleServer()
                    .setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
                    .setPassword(redisProperties.getPassword());
        }*/
        save("testLock", requestId);
        String r = find("testLock");
        log.info("查询redis结果 = {}", r);

        ResilientRedisLock lock = new ResilientRedisLock(jedisCluster);
        String lockKey = "lock:task.test";
        //String requestId = UUID.randomUUID() + "-" + Thread.currentThread().getId();
        log.info("requestId={}, lockKey={}, 开始处理", requestId, lockKey);
        if (lock.tryLock(lockKey, requestId, ttl, 5000)) {
            try {
                // 可重入
                lock.tryLock(lockKey, requestId, ttl, 1000);
                // 执行业务逻辑
                log.info("requestId={}, lockKey={}, 开始处理业务", requestId, lockKey);
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.info("requestId={}, lockKey={}, 处理业务完成", requestId, lockKey);
            } finally {
                lock.releaseLock(lockKey, requestId);
                lock.releaseLock(lockKey, requestId); // 需释放与加锁次数相同
            }
        } else {
            // 获取锁失败处理逻辑
            log.debug("已经被锁定");
        }

        return requestId+"处理完成";
    }


    public void save(String key, String value) {
        jedisCluster.set(key, value);
    }

    public String find(String id) {
        String s = jedisCluster.get(id);
        System.out.println(s);
        return s;
    }
}
